<template>
  <div>
    <Form :label-width="100" ref="form1" :model="form1">
      <Row class="query-form2" v-if="!switchFlag">
        <Col span="8">
          <FormItem label="二级集团：" prop="workDate">
            <Select v-model="form1.twoLevelOrgName" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgName" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="企业名称：" prop="orgId">
            <company-select v-model="form1.belongOrgName" style="width:100%"></company-select>
          </FormItem>
        </Col>
        <Col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="searchQuery">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">展开
              <Icon type="ios-arrow-down"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="二级集团：" prop="workDate">
            <Select v-model="form1.twoLevelOrgName" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgName" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="企业名称：" prop="orgId">
            <company-select v-model="form1.belongOrgName" style="width:100%"></company-select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作业时间：" prop="workDate">
            <DatePicker type="daterange" v-model="form1.workDate" split-panels placeholder="请选择"
                        style="width: 100%"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="作业单位：" prop="operateOrgName">
            <Input type="text" v-model="form1.operateOrgName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="许可类型：" prop="modelType">
            <Select v-model="form1.modelType">
              <Option v-for="item in modelTypeList" :value="item.codingCodeId" :key="item.codingCodeId">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作业部门：" prop="workDept">
            <Input type="text" v-model="form1.workDept"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="备案查询：" prop="beian">
            <i-switch v-model="form1.beian">
              <span slot="open">是</span>
              <span slot="close">否</span>
            </i-switch>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作业状态：" prop="modelType">
            <Select v-model="form1.ptwStatus">
              <Option v-for="item in ptwStatusList" :value="item.codingCodeId" :key="item.codingCodeId">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="任务名称：" prop="planName">
            <Input type="text" v-model="form1.planName"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form2">
        <Col span="24">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="searchQuery">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text">收起
              <Icon type="ios-arrow-up"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button class="ivu-btn-add"  icon="md-cloud-download" :loading="buttonLoading" @click="exportData">导出</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :loading="loading" border :columns="columns1" :data="dataTable"
           width="100%" :height="tableHeight" highlight-row stripe size="small"
            @on-sort-change="onSortChange"></Table>
    <Row type="flex" justify="end">
      <i-col>
        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total
              show-sizer show-elevator/>
      </i-col>
    </Row>
    <Modal :transfer=false v-model="model1" :width=900>
      <Tabs>
        <TabPane label="历史记录">
          <Table ref='table1' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                 :loading="loading2"
                 :data="history" width="100%" :height="450" highlight-row stripe size="small"></Table>
        </TabPane>
        <TabPane label="流程图">
          <div style="height: 450px; overflow-y: auto; overflow-x: auto">
            <img :src="imgUrl">
          </div>
        </TabPane>
      </Tabs>
      <div slot="footer">
        <Button @click="model1=false" class="ivu-btn-save">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>

var cascaderDom = () => import('@/components/cascader-dom.vue');
import companySelect from "../../../../components/company-select.vue"
import {Api} from '../../../../api/index.js'
import {sessionStorage, cookie} from '../../../../common/cacheUtils.js';

export default {
  components: {
    cascaderDom,companySelect
  },
  data() {
    return {
      defaultLabel: sessionStorage('userId').getObject('userId').companyName,
      orgLists: [],
      userInfo: sessionStorage('userId').getObject('userId'),
      twoLevelOrgs: [],
      sortMap:{},
      buttonLoading: false,
      orgLoading: false,
      imgUrl: '',
      loading: false,
      loading2: false,
      model1: false,
      rootOrgId: '',
      switchFlag: true,
      ptwData: {},
      workItems: [],
      modelData: {},
      detailRow1: 'detailRow1',
      detailRow2: 'detailRow2',
      checkDatas: [],
      others: [],
      form1: {workDate:["",""]},
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      columns1: [
        {
          title: '序号',
          width: 100,
          align: 'center',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          minWidth: 150,
          title: '任务名称',
          key: 'planName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '任务许可证类型',
          key: 'modelTypeName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '所属单位',
          key: 'belongOrgName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '作业单位',
          key: 'operateOrgName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '作业部门',
          key: 'workDept',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '作业开始时间',
          key: 'applyStartDate',
          align: 'center',
          sortable: 'custom',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.applyStartDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '作业结束时间',
          key: 'applyEndDate',
          align: 'center',
          sortable: 'custom',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.applyEndDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '状态',
          key: 'status',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              (params.row.ptwStatus == '0' ? '未上报' :
                  params.row.ptwStatus == '1' ? '审批中' :
                      params.row.ptwStatus == '2' ? '作业中' :
                          params.row.ptwStatus == '3' ? '已关闭' :
                              params.row.ptwStatus == '4' ? '已过期' :
                                  params.row.ptwStatus == '5' ? '延期关闭' : '')
            ]);
          }
        },
        {
          title: '操作',
          align: 'center',
          key: 'view',
          fixed: 'right',
          width: 200,
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.showData(params.row, 1);
                  }
                }
              }, '查看'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: params.row.ptwStatus != '0' ? '' : '#d0d0d0',
                  pointerEvents: params.row.ptwStatus != '0' ? '' : 'none'
                },
                on: {
                  click: () => {
                    this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                    this.showHistory(params.row);
                  }
                }
              }, '审批记录'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: params.row.ptwStatus != '0' ? '' : '#d0d0d0',
                  pointerEvents: params.row.ptwStatus != '0' ? '' : 'none'
                },
                on: {
                  click: () => {
                    this.exportWord(params.row.ptwId, params.row.modelType, params.row.planName + "-" + params.row.modelTypeName);
                  }
                }
              }, '导出')
            ]);
          }
        }
      ],
      currentOrgId: '',
      currentOrgName: '',
      setCurrentName: {},
      dataTable: [],
      add: false,
      ptwTypeList: [],
      workGradeList: [],
      ptwStatusList: [
        {codingCodeId: '0', codingName: "未上报"},
        {codingCodeId: '1', codingName: "审批中"},
        {codingCodeId: '2', codingName: "审批通过"},
        {codingCodeId: '3', codingName: "已关闭"},
        {codingCodeId: '4', codingName: "已延期"},
        {codingCodeId: '5', codingName: "延期关闭"}
      ],
      tableHeight: 10,
      deleteRows: [],
      history: [],
      columns2: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          width: 180,
          title: '审批时间',
          key: 'endTime',
          align: 'center',
        },
        {
          width: 185,
          title: '节点名称',
          key: 'name',
          align: 'center',
        },
        {
          width: 120,
          title: '审批人',
          key: 'userName',
          align: 'center'
        },
        {
          width: 100,
          title: '审批意见',
          key: 'route',
          align: 'center'
        },
        {
          width: 200,
          title: '备注',
          key: 'opinions',
          align: 'center'
        },
      ],
      modelTypeList: []
    }
  },
  mounted() {
    var currentTime = new Date();
    var threeMonthsAgo = new Date(currentTime.setMonth(currentTime.getMonth()-3));
    this.form1.workDate = [this.formatDate(threeMonthsAgo,"'yyyy-MM-dd'"),this.formatDate(new Date(),"'yyyy-MM-dd'")];
    this.rootOrgId = sessionStorage('userId').getObject('userId').orgInfo.parentId;
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query();
    this.selectCodingSort();
    this.queryTwoOrgInfo();
  },
  methods: {
    searchQuery(){
      this.pagedata.currentPage = 1
      this.query();
    },
    queryTwoOrgInfo() {
      if (sessionStorage('userId').getObject('userId').companyId != '18000000') {
        this.twoLevelOrgs.push({
          orgId: sessionStorage('userId').getObject('userId').twoLevelOrgId,
          orgName: sessionStorage('userId').getObject('userId').twoLevelOrgName
        });
      } else {
        this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
          this.twoLevelOrgs = res.data.data
        }).catch(e => {
        })
      }
    },
    remoteMethodSelectOrg(query) {
      if (query !== '') {
        this.orgLists = [];
        this.orgLoading = true;
        this.$http.get(Api.queryOrgList + "?companyId=" + this.userInfo.companyId + "&orgName=" + query + "&fromPage=1&pageSize=1000").then(res => {
          this.orgLists = res.data.data;
          this.orgLoading = false;
        }).catch(e => {
          this.orgLoading = false;
          this.$Message.error('请求失败');
        })
      } else {
        this.orgLoading = false;
      }
    },
    selectCodingSort() {
      this.$http.get(Api.queryCodeDetailBySortId + '/ptw-100001', {params: {}}).then((res) => {
        this.modelTypeList = res.data.data;
      })
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 132;
      } else {
        this.tableHeight = this.tableHeight + 132;
      }
    },
    closeWorkFlow() {

    },
    reportWorkFlow(row) {
      let userId = sessionStorage('userId').getObject('userId').userId;
      this.$http.post(Api.startPtwTicketWorkFlow + '/task/' + row.ptwId + "/" + userId, {}).then((res) => {
        this.query();
      })
    },
    setBelongOrgId(data) {
      this.form1.belongOrgId = data[data.length - 1];
    },
    setBelongOrgName(data) {
      this.form1.belongOrgName = data;
    },
    setOperateOrgId(data) {
      this.form1.operateOrgId = data[data.length - 1];
    },
    setOperateOrgName(data) {
      this.form1.operateOrgName = data;
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    deleteData(row) {
      let url = Api.deletePtwPlan;
      this.$http.get(url, {params: {planId: row.planId}}).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    onSortChange(custom){
      this.sortMap.sortKey = custom.key;
      this.sortMap.sortOrder = custom.order;
      this.query();
    },
    exportWord(ptwId, ptwType, ptwName) {
      this.isSpin = true;
      this.$http.get(Api.exportPtwWord + "?ptwId=" + ptwId + "&type=" + ptwType, {
        responseType: 'arraybuffer'
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: "application/msword"
        })
        aLink.href = URL.createObjectURL(blob);
        aLink.download = ptwName + ".doc" //标题
        aLink.click();
        document.body.appendChild(aLink);
        this.isSpin = false;
      }).catch(e => {
        this.$Message.error("数据获取失败");
        this.isSpin = false;
      })
    },
    showHistory(row) {
      this.model1 = true;
      this.loading2 = true;
      this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
        this.history = res.data;
        this.loading2 = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    query() {
      this.loading = true;
      let data = {
        currentPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        belongOrgName: sessionStorage('userId').getObject('userId').companyName
      }
      if (this.form1.workDate[0] != '' && this.form1.workDate[1] != '') {
        this.form1.applyStartDate = this.formatDate(new Date(this.form1.workDate[0]), 'yyyy-MM-dd') + " 00:00";
        this.form1.applyEndDate = this.formatDate(new Date(this.form1.workDate[1]), 'yyyy-MM-dd') + " 24:00";
      }else{
        this.form1.applyStartDate = "";
        this.form1.applyEndDate = "";
      }
      let twoLevelOrgId = sessionStorage('userId').getObject('userId').twoLevelOrgId
      if (this.form1.beian == true && this.Common.belongOrgId.includes(twoLevelOrgId)) {
        this.form1.twoLevelOrgId = twoLevelOrgId
      } else {
        delete this.form1['twoLevelOrgId']
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      data = Object.assign(data, JSON.parse(JSON.stringify(this.sortMap)));
      let url = Api.getPtwList;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        this.pagedata.total = res.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    exportData(){
      this.buttonLoading = true;
      let data = {
        belongOrgName: sessionStorage('userId').getObject('userId').companyName
      }
      if (this.form1.workDate[0] != '' && this.form1.workDate[1] != '') {
        this.form1.applyStartDate = this.formatDate(new Date(this.form1.workDate[0]), 'yyyy-MM-dd') + " 00:00";
        this.form1.applyEndDate = this.formatDate(new Date(this.form1.workDate[1]), 'yyyy-MM-dd') + " 24:00";
      }else{
        this.form1.applyStartDate = "";
        this.form1.applyEndDate = "";
      }
      let twoLevelOrgId = sessionStorage('userId').getObject('userId').twoLevelOrgId
      if (this.form1.beian == true && this.Common.belongOrgId.includes(twoLevelOrgId)) {
        this.form1.twoLevelOrgId = twoLevelOrgId
      } else {
        delete this.form1['twoLevelOrgId']
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      data = Object.assign(data, JSON.parse(JSON.stringify(this.sortMap)));
      let url = Api.exportPtwList;
      this.$http.get(url, {params: data,responseType: 'arraybuffer' }, {
             //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel"
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "作业记录数据.xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
        this.buttonLoading = false;
      }).catch(e => {
        console.log(e)
        this.buttonLoading = false;
        this.$Message.error("导出失败")
      })
    },
    reset() {
      this.form1 = {workDate: ['', '']};
      var currentTime = new Date();
      var threeMonthsAgo = new Date(currentTime.setMonth(currentTime.getMonth()-3));
      this.form1.workDate = [this.formatDate(threeMonthsAgo,"'yyyy-MM-dd'"),this.formatDate(new Date(),"'yyyy-MM-dd'")];
      this.query();
    },
    addInfo() {
      let obj = {};
      this.$router.push({name: 'ptwTicketEdit', params: {'data': obj}});
    },
    showData(data, flag) {
      if (flag == '1') {
        this.$router.push({name: 'ptwTicketRecordView', params: {'data': data}});
      } else
        this.$router.push({name: 'ptwTicketEdit', params: {'data': data}});
    },
    cancel() {

    },
    formatDate(date, fmt) {
      if (typeof date == 'string') {
        return date;
      }
      if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
      if (!date || date == null) return null;
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
      return fmt
    },
  }
}
</script>
<style lang='css' scoped>
@import '../../../../index.css';
</style>
